/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.settings;

import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.DialogInterface.OnClickListener;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemProperties;
import android.preference.Preference;
import android.preference.PreferenceGroup;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.content.res.Resources.NotFoundException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import com.hisense.settings.MyLog;
import com.google.android.tv.common.TvIntent;
import com.google.android.tv.settings.TvSettings;

public class TvDeviceInfoSettings extends DeviceInfoSettings {
	private static final String LOG_TAG = "TvDeviceInfoSettings";
	private static final String KEY_DEVICE_NAME_SECTION = "device_name_settings";
	private static final int DIALOG_DEVICE_NAME_SETTER = 1000;

	private DeviceNameSetterDialog mDeviceNameSetter;
	private Preference mDeviceNamePref;
	// add for hisense remote control update
	private static final String KEY_CONTAINER = "container";
	private static final String KEY_REMOTE_UPDATE = "remote_update_settings";

	/**
	 * the following is customized Hisense legal
	 * 
	 * @author libaocheng@hisense.com
	 */
	private static final String HISENSE_KEY_LICENSE = "hisense_legal";
	private static long file_len = 0;
	private static final String null_string = "read deviceid file is null";
	private static final String tt = "device_id file not found";
	private static final String DEVICEID_FILE = "/factory_setting/Device_ID";
	private static final String HISENSE_DEVICEID = "hisense_deviceid";

	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			updateDeviceName();
		}
	};

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		getActivity().setTitle(R.string.about_settings);
		mDeviceNamePref = findPreference(KEY_DEVICE_NAME_SECTION);
		updateDeviceName();
		//hisense add begin
		setdeviceid();
		try {
			setSoftWareVserison();
		} catch (Exception e) {
			MyLog.w(LOG_TAG, "setSoftWareVserison wrong need check");
		}
		/*
		 * if (Utils.isInStrippedMode(getContentResolver())) { Preference
		 * tutorial = findPreference("system_tutorial");
		 * getPreferenceScreen().removePreference(tutorial); }
		 */// this may add for press F3 to skip tutorial
		/*
         * Settings is a generic app and should not contain any device-specific
         * info.
         */
        final Activity act = getActivity();
        // These are contained in the "container" preference group
        PreferenceGroup parentPreference = (PreferenceGroup) findPreference(KEY_CONTAINER);
		boolean hisenselegal = Utils
				.updatePreferenceToSpecificActivityOrRemove(
						act,
						parentPreference,
						HISENSE_KEY_LICENSE,
						Utils.UPDATE_PREFERENCE_FLAG_SET_TITLE_TO_MATCHING_ACTIVITY);

		MyLog.d(LOG_TAG, "hisense legal" + hisenselegal);
		// hisense add end
	}

	@Override
	public void onResume() {
		super.onResume();

		IntentFilter filter = new IntentFilter();
		filter.addAction(TvIntent.ACTION_USER_DEVICE_NAME_UPDATED);
		getActivity().registerReceiver(mReceiver, filter);
	}

	@Override
	public void onPause() {
		getActivity().unregisterReceiver(mReceiver);
		super.onPause();
	}

	private void updateDeviceName() {
		mDeviceNamePref.setSummary(TvSettings.System
				.getUserDeviceName(getActivity()));
	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		if (preference == mDeviceNamePref) {
			showDialog(DIALOG_DEVICE_NAME_SETTER);
		} else if (preference.getKey().equals(KEY_REMOTE_UPDATE)) {
			try {
				Intent intent = new Intent("com.hisense.action.REMOTEUPDATE");
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getActivity().startActivity(intent);
			} catch (NotFoundException e) {
				MyLog.d(LOG_TAG, "Activity Not found");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

	@Override
	public Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DEVICE_NAME_SETTER:
			mDeviceNameSetter = new DeviceNameSetterDialog(getActivity(),
					(String) mDeviceNamePref.getSummary(),
					new DeviceNameSetterDialog.OnDeviceNameSetListener() {
						public void onDeviceNameSet(String name) {
							if (name != null) {
								name.trim();
								TvSettings.System.setUserDeviceName(
										getActivity(), name);
							}
						}
					});
			mDeviceNameSetter.setOnCancelListener(null);
			mDeviceNameSetter.setButton(DialogInterface.BUTTON_NEGATIVE,
					getString(R.string.cancel), (OnClickListener) null);
			return mDeviceNameSetter;

		default:
			return super.onCreateDialog(id);
		}
	}

	private void setdeviceid() {
		File file = new File(DEVICEID_FILE);
		MyLog.d(LOG_TAG, "***************setdeviceid file.exists()"+file.exists());
		Reader reader = null;
		char[] tempchars = new char[23];
		String st = null;

		try {
			reader = new InputStreamReader(new FileInputStream(DEVICEID_FILE));
			file_len = file.length();
			MyLog.d(LOG_TAG, "***************file_len= " + file_len);
			reader.read(tempchars);
			String str = new String(tempchars);
			MyLog.d(LOG_TAG, "***************device_ID:str= " + str);
			if (file_len == 0) {
				setStringSummary(HISENSE_DEVICEID, null_string);
			} else {
				setStringSummary(HISENSE_DEVICEID, str);
			}

			reader.close();

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			setStringSummary(HISENSE_DEVICEID, tt);
		} catch (Exception e) {
			setStringSummary(HISENSE_DEVICEID, "read file have error");
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
					setStringSummary(HISENSE_DEVICEID, "read file have error");
				}
			}
		}
	}

	private void setSoftWareVserison(){
		String SWver = SystemProperties.get("ro.build.hisense.softwarever", " ");
		MyLog.d(LOG_TAG, "***************1*SWver= "+SWver);
		String mVersion = Build.VERSION.INCREMENTAL;
		MyLog.d(LOG_TAG, "***************1*mVersion= "+mVersion);
        String[] mDateArray = mVersion.split("\\.");
        if(mDateArray.length>=3){
        	String str = null;
            str = mDateArray[2];
            MyLog.i(LOG_TAG, "get build date= " + str);
            String year = str.substring(0,4);
    		//Log.d(LOG_TAG, "**************year= "+year);
    		int iyear = Integer.parseInt(year);
    		//Log.d(LOG_TAG, "**************year = "+iyear);
    		char cyear = (char)('A'+(iyear - 2010));	
    		if(SWver!=null&&SWver.length() < 12)
    		{
    			MyLog.d(LOG_TAG, "**********Software version invalid !!! Use default");
    			SWver = "V0000.01.01d";
    		}
            String fullVer = SWver + '.'+cyear+str.substring(4);
    		setStringSummary("software_version", fullVer);
        }else{
        	//String SWver = SystemProperties
    		//		.get("ro.build.hisense.softwarever", " ");
    		//MyLog.d(LOG_TAG, "***************SWver= " + SWver);
    		String date = SystemProperties.get("ro.build.date", "");
    		MyLog.d(LOG_TAG, "***************date= " + date);
    		String[] mGoogleDateArray = date.split(" ");
    		String month = null;
    		month = mGoogleDateArray[1];
    		if (month.equalsIgnoreCase("Jan")) {
    			month = "01";
    		} else if (month.equalsIgnoreCase("Feb")) {
    			month = "02";
    		} else if (month.equalsIgnoreCase("Mar")) {
    			month = "03";
    		} else if (month.equalsIgnoreCase("Apr")) {
    			month = "04";
    		} else if (month.equalsIgnoreCase("May")) {
    			month = "05";
    		} else if (month.equalsIgnoreCase("Jun")) {
    			month = "06";
    		} else if (month.equalsIgnoreCase("Jul")) {
    			month = "07";
    		} else if (month.equalsIgnoreCase("Aug")) {
    			month = "08";
    		} else if (month.equalsIgnoreCase("Sep")) {
    			month = "09";
    		} else if (month.equalsIgnoreCase("Oct")) {
    			month = "10";
    		} else if (month.equalsIgnoreCase("Nov")) {
    			month = "11";
    		} else if (month.equalsIgnoreCase("Dec")) {
    			month = "12";
    		}
    		MyLog.d(LOG_TAG, "month:" + month);
    		String day = date.substring(8, 9);
    		if(day.equals(" ")){
    			day="0";
    		}
    		MyLog.d(LOG_TAG, "day:" + day);
    		day=day+date.substring(9,10);
    		String year = mGoogleDateArray[mGoogleDateArray.length-1];
    		MyLog.d(LOG_TAG, "mDateArray.length:" + mGoogleDateArray.length);
    		MyLog.d(LOG_TAG, "year:" + year);
    		int iyear = Integer.parseInt(year);
    		MyLog.d(LOG_TAG, "iyear:" + iyear);
    		char cyear = (char) ('A' + (iyear - 2010));
    		String fullVer = SWver + '.' + cyear + month + day;
    		String mdate = month + date.substring(9, 11);
    		MyLog.d(LOG_TAG, "mdate" + mdate);
    		if (SWver != null && SWver.length() < 12) {
    			MyLog.d(LOG_TAG,
    					"**********Software version invalid !!! Use default");
    			SWver = "V0000.01.01d";
    		}
    		setStringSummary("software_version", fullVer);
        }
	}
	private void setStringSummary(String preference, String value) {
		try {
			findPreference(preference).setSummary(value);
		} catch (RuntimeException e) {
			findPreference(preference).setSummary(
					getResources().getString(R.string.device_info_default));
		}
	}
}
